package com.at.state14;

import com.at.bean.WaterSensor;
import com.at.functions5.WaterSensorMapFunction3;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * TODO 需求： 检测每种传感器的水位值，如果连续的两个水位值超过10，就输出报警。
 *
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/9/30 14:46
 */
public class KeyedValueStateDemo1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 7777)
                .map(new WaterSensorMapFunction3())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((element, ts) -> element.getTs() * 1000L)
                );

        sensorDS.keyBy(r -> r.getId())
                .process(
                        new KeyedProcessFunction<String, WaterSensor, String>() {
                            // 用单个值，在key情况下会冲突
//                            int lastVc = 0;
                            // TODO 1、定义状态
                            ValueState<Integer> lastVcState;

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                super.open(parameters);
                                // TODO 2、在open方法中，初始化状态
                                lastVcState = getRuntimeContext().getState(new ValueStateDescriptor<>("lastVcState", Types.INT));
                            }

                            @Override
                            public void processElement(WaterSensor value, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                                // 1、取出上一条数据的水位值
                                Integer lastVc = lastVcState.value(); // 取出值状态里的数据

                                // 2、求差值的绝对值，判断是否超过10
                                Integer vc = value.getVc();
                                if (lastVc != null) {
                                    if (Math.abs(vc - lastVc) > 10) {
                                        out.collect("传感器=" + value.getId() + "===>当前水位值=" + vc + ", 与上一条水位值=" + lastVc + ",相差超过10！！！");
                                    }
                                }

                                // 3、保存更新自己的水位值
                                lastVcState.update(vc);

//                                Integer vc = value.getVc();
//                                if (Math.abs(vc - lastVc) > 10) {
//                                    out.collect("传感器=" + value.getId() + "===>当前水位值=" + vc + ", 与上一条水位值=" + lastVc + ",相差超过10！！！");
//                                }
//                                lastVc = vc;
                            }
                        }
                )
                .print();

        env.execute();
    }
}
